package logic

import (
	"MyBlogv2/blog-common/es"
	"MyBlogv2/blog-common/helper"
	"MyBlogv2/blog-common/models"
	"context"
	"github.com/jinzhu/copier"
	"math"
	"strings"

	"MyBlogv2/Servers/Article/article"
	"MyBlogv2/Servers/Article/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type SearchArticleByContentLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSearchArticleByContentLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SearchArticleByContentLogic {
	return &SearchArticleByContentLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SearchArticleByContentLogic) SearchArticleByContent(in *Article.ArticleRequest) (*Article.SearchArticleByContentVoList, error) {
	var searchArticleByContentVo []models.SearchArticleByContentVo
	var articleEsList []models.ArticleEs
	keyword := in.Keyword
	if keyword != "" {
		//models.Db.Model(new(models.ArticleVo)).
		//	Table("t_article a").
		//	Select("a.*,c.category_name as category_name").
		//	Joins("left join t_category c on a.category_id = c.id").
		//	Where("a.status = ?", define2.PUBLIC_ARTICLE).
		//	Where("a.article_content like ?", "%"+keyword+"%").
		//	Find(&articleVo)
		articleEsList, _ = es.SearchArticleByContent(keyword)
		copier.Copy(&searchArticleByContentVo, &articleEsList)
	} else {
		//models.Db.Model(new(models.ArticleVo)).
		//	Table("t_article a").
		//	Select("a.*,c.category_name as category_name").
		//	Joins("left join t_category c on a.category_id = c.id").
		//	Where("a.status = ?", define2.PUBLIC_ARTICLE).
		//	Find(&articleVo)
		articleEsList, _ = es.SearchArticleByContent("")
		copier.Copy(&searchArticleByContentVo, &articleEsList)
	}
	if len(searchArticleByContentVo) != 0 {
		index := -1
		for i, v := range searchArticleByContentVo {
			index = -1
			content := v.ArticleContent
			index = strings.Index(strings.ToLower(content), strings.ToLower(keyword))
			if index != -1 {
				end := math.Min(float64(len(content)), float64(index+len(keyword)+50))

				highlighted := keyword + string(content[index+len(keyword):int(end)])
				searchArticleByContentVo[i].ArticleContent = strings.TrimRight(helper.StripMarkdown(highlighted), "�")
			}
		}
		var searchArticleByContentVoList []*Article.SearchArticleByContentVo
		copier.Copy(&searchArticleByContentVoList, &searchArticleByContentVo)
		return &Article.SearchArticleByContentVoList{
			SearchArticleByContentVoList: searchArticleByContentVoList,
		}, nil

	}
	return &Article.SearchArticleByContentVoList{}, nil

}
